<script setup>
import { onMounted,ref } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus'; // 引入 Element Plus 的消息提示
import Navbar from '@/components/Navbar.vue';

const tokenvalue = window.localStorage.getItem('token');

// 设置 Axios 默认配置
axios.defaults.headers.common['token'] = `${tokenvalue}`;


const tableData = ref([]);
const dialogTitle = ref('');
const isAdding = ref(true);
const searchId = ref('');

const fetchData = async () => {
  try {
    const response = await axios.get('http://localhost:8000/crud/getAll');
    tableData.value = response.data.map(row => ({
      ...row,
    }));
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};

const reloadTable = () => {
  window.location.reload();
};

const handleEdit = (index, row) => {
  console.log(`点击了第${index + 1}行的修改按钮`, row);
  // 复制当前行的数据到tempRow
  tempRow.value = { ...row };
  // 显示对话框
  dialogTitle.value = '修改数据';
  isAdding.value = false;
  dialogVisible.value = true;
};

const handleDelete = async (index, row) => {
  console.log(`点击了第${index + 1}行的删除按钮`, row);
  try {
    // 发送 DELETE 请求
    const response = await axios.delete(`http://localhost:8000/crud/delete/${row.id}`);
    if (response.status === 200) {
      // 从数组中移除该行数据
      tableData.value.splice(index, 1);
      ElMessage.success('删除成功');
    }
  } catch (error) {
    console.error('Error deleting data:', error);
    ElMessage.error('删除失败，请重试');
  }
};

const handleAdd = () => {
  console.log('点击了新增按钮');
  // 清空表单数据
  tempRow.value = {};
  // 显示对话框
  dialogTitle.value = '新增数据';
  isAdding.value = true;
  dialogVisible.value = true;
};

const handleSearchById = async () => {
  console.log('点击了根据id查找按钮');
  try {
    const id = searchId.value;
    if (!id) {
      ElMessage.warning('请输入ID');
      return;
    }

    const response = await axios.get(`http://localhost:8000/crud/get/${id}`);
    if (response.status === 200 && response.data) {
      const foundRow = response.data;
      // 清空表格内容
      tableData.value = [];
      // 将找到的数据添加到表格中
      tableData.value.push({ ...foundRow });
      ElMessage.success('查找成功');
    } else {
      ElMessage.warning('未找到该ID');
    }
  } catch (error) {
    console.error('Error searching by ID:', error);
    ElMessage.error('查找失败，请重试');
  }
};

const dialogVisible = ref(false);
const tempRow = ref({});


// 文件上传
const fileName = ref('');
const selectedFile = ref(null);
const onFileChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    fileName.value = file.name;
    selectedFile.value = file;
    console.log(`文件名: ${file.name}`);
  }
};


const submitAddOrEdit = async () => {
  if(!selectedFile.value){  selectedFile.value = tempRow.value.pic; }
  if (!selectedFile.value) {
    // console.error('没有选择文件');
    ElMessage.error('没有选择文件');
    return;
  }

  const formData = new FormData();
  formData.append('file', selectedFile.value);

  try {
    const response = await axios.post('http://localhost:8000/crud/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    ElMessage.success('文件上传成功');
    tempRow.value.pic= `/src/assets/images/${fileName.value}`;
    console.log(tempRow.value.pic);   
    fileName.value = '';
    selectedFile.value = null;
  } catch (error) {
    ElMessage.error('没有上传新文件');
    console.error('没有上传新文件:', error);
  }

  try {
    if (isAdding.value) {
      // 格式化数据
      tempRow.value.date = new Date(tempRow.value.date).toISOString().slice(0, 10);
      // 发送 POST 请求添加新数据
      const response = await axios.post('http://localhost:8000/crud/add', tempRow.value);
      if (response.status === 200) {
        tableData.value.push({ ...tempRow.value });
        dialogVisible.value = false; // 关闭对话框
        fetchData();
        ElMessage.success('新增成功');
      }
    } else {
      // 格式化数据
      tempRow.value.date = new Date(tempRow.value.date).toISOString().slice(0, 10);
      // 发送 POST 请求更新数据
      const response = await axios.post('http://localhost:8000/crud/update', tempRow.value);
      if (response.status === 200) {
        // 找到对应的索引并更新
        const index = tableData.value.findIndex(item => item.id === tempRow.value.id);
        if (index !== -1) {
          tableData.value[index] = { ...tempRow.value };
        }
        dialogVisible.value = false; // 关闭对话框
        ElMessage.success('编辑成功');
        fetchData();
      }
    }
  } catch (error) {
    console.error('Error submitting data:', error);
    ElMessage.error('提交失败，请重试');
  }
};

onMounted(() => {
  fetchData();
});
</script>

<template>
  <div>
    <Navbar />
      <!-- 数据表格 -->
      <div>
          <!-- 搜索功能 -->
          <div>
              <el-input v-model="searchId" placeholder="请输入ID" style="width: 150px;"></el-input>
              <el-button type="primary" @click="handleSearchById" style="margin-left: 10px;">搜索</el-button>
          </div>
          <!-- 新增按钮 -->
          <el-button type="primary" @click="handleAdd" style="margin-bottom: 20px;">新增</el-button>
           <!-- 刷新表格按钮 -->
          <el-button type="primary" @click="reloadTable" style="margin-left: 10px; margin-bottom: 20px;">重新加载表格</el-button>
          <el-table :data="tableData" style="width: 100%">
              <el-table-column prop="id" label="ID" width="80"></el-table-column>
              <el-table-column prop="descriptive" label="描述" width="180"></el-table-column>
              <el-table-column prop="date" label="日期" width="180"></el-table-column>
              <el-table-column prop="pic" label="图片">
              <template #default="scope">
                  <img :src="scope.row.pic" alt="图片预览" style="max-width: 100px; max-height: 100px;">
                  <!-- <img :src="'/src/assets/images/心海.jpg'" alt="图片预览" style="max-width: 100px; max-height: 100px;"> -->
              </template>
              </el-table-column>
              <!-- 新增一列用于显示修改和删除按钮 -->
              <el-table-column label="操作" width="200">
              <template #default="scope">
                  <el-button type="text" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
                  <el-button type="text" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </template>
              </el-table-column>
          </el-table>
      </div> 

      <!-- 编辑对话框 -->
      <el-dialog v-model="dialogVisible" :title="dialogTitle">
        <el-form :model="tempRow" label-width="80px">
          <el-form-item label="ID">
            <el-input v-model="tempRow.id" disabled="!isAdding"></el-input>
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="tempRow.descriptive"></el-input>
          </el-form-item>
          <el-form-item label="日期">
            <el-date-picker v-model="tempRow.date" ></el-date-picker>
          </el-form-item>
          <el-form-item label="图片">
            <div>
              <input type="file" id="fileInput" accept=".jpg,.png,.jpeg" @change="onFileChange" />
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitAddOrEdit">确定</el-button>
          </span>
        </template>
      </el-dialog>     
  </div>
</template>

<style scoped>

</style>